package com.aiwhose.aiwhosefile.aop;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aiwhose.aiwhosecore.bean.system.ApiLogs;
import jakarta.annotation.PreDestroy;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.math.BigDecimal;
import java.util.Arrays;

@Aspect
@Component
public class LoggingAspect {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义切点，匹配指定包下所有Controller类的所有方法
    @Around("execution(* com.aiwhose.aiwhosefile.controller.*.*(..))")
    public Object controllerPointcut(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行方法
        Object proceed = joinPoint.proceed();
        try {
            long startTime = System.currentTimeMillis();
            // 获取请求属性
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String requestPath = attributes.getRequest().getRequestURI();
            String httpMethod = attributes.getRequest().getMethod();


            // 获取方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//            获取IP
            HttpServletRequest request = attributes.getRequest();
            // 尝试从 X-Forwarded-For 头部获取真实IP地址
            String ipAddress = request.getHeader("X-Forwarded-For");
            if (ipAddress == null || ipAddress.isEmpty()) {
                ipAddress = request.getRemoteAddr();
            }
            // 日志记录
            ApiLogs apiLogs = new ApiLogs();
            apiLogs.setRequestPath(requestPath);
            apiLogs.setProjectName("aiwhosefile");
            apiLogs.setHttpMethod(httpMethod);
            apiLogs.setController(signature.getDeclaringTypeName());
            apiLogs.setMethod(signature.getName());

            Object[] args = joinPoint.getArgs();

            String[] params = new String[args.length];
            for (int i = 0; i < args.length; i++) {
                if (ObjectUtil.isEmpty(args[i])) {
                    params[i] = "null";
                    continue;
                }
                params[i] = StrUtil.toString(args[i]);

            }
            apiLogs.setArguments(Arrays.toString(params));

            apiLogs.setIpAddress(ipAddress);


            apiLogs.setResponse(ObjectUtil.toString(proceed));

            long elapsedTime = System.currentTimeMillis() - startTime;
            apiLogs.setExecutionTime(BigDecimal.valueOf(elapsedTime));
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            apiLogs.setCreateBy(StrUtil.toString(tokenInfo.getLoginId()));
            rabbitTemplate.convertAndSend("system.apilog.exchange", "apilog", apiLogs);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // 执行方法
        return proceed;
    }

    @PreDestroy
    public void onDestroy() {

    }

}
